package cn.ehanghai.htz.thread;

import cn.ehanghai.htz.common.utils.ApplicationContextUtil;
import cn.ehanghai.htz.domain.Position;
import cn.ehanghai.htz.service.PositionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @Author: xumf
 * @Date: 2019/7/5 11:13
 */
public class PositionSaveQueueThread extends Thread{

    private static final Logger logger=LoggerFactory.getLogger(PositionSaveQueueThread.class);

    private static Queue<Position> workQueue=new ConcurrentLinkedQueue<>();

    PositionService positionService= (PositionService) ApplicationContextUtil.getBean(PositionService.class);

    @Override
    public void run() {
        logger.warn("PositionSaveQueueThread----------服务已开启");
        while (true) {
            try {
                if(workQueue.size()>0){
                    Position position = workQueue.poll();
                    if(position!=null && position.getMmsi()!=null
                            && position.getLat()!=null && position.getLon()!=null) {
                        Position p= positionService.selectBymmsi(position.getMmsi());
                        if(p==null){
                            positionService.insert(position);
                        }else{
                            p.setSpeedOverGround(position.getSpeedOverGround());
                            p.setCourseOverGround(position.getCourseOverGround());
                            p.setLon(position.getLon());
                            p.setLat(position.getLat());
                            p.setRateOfTurn(position.getRateOfTurn());
                            p.setUpdateDate(position.getUpdateDate());
                            positionService.updatePosition(p);
                        }
                    }
                }
                else {
                    Thread.sleep(1000);
                }
            }catch (Exception e){
                logger.error("position线程异常！！",e);
            }
        }
    }

    public static void push(Position position) {
        try {
            if (position != null) {
                workQueue.offer(position);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
